package com.zxy.service;

import cn.echo.exception.BizException;
import cn.echo.threadlocal.LocalUserUtils;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;

import com.zxy.dao.UserDao;
import com.zxy.dao.UserRolesDao;
import com.zxy.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserService {
    //    密钥
    @Value("${TokenKey}")
    private String tokenKey;
    @Autowired
    private UserDao userDao;

    @Autowired
    private UserRolesDao userRolesDao;
    public String register(RegisterInfo registerInfo) {
//        省略校验

        User user = userDao.select(registerInfo.getTel());
        if (ObjUtil.isNotEmpty(user)) {
            throw new BizException(405, "手机号已存在");
        }

//        如果手机号没有注册，就需要存进数据库中
        int rowNum = userDao.insert(registerInfo);

        if (rowNum != 1) {
            throw new BizException(406, "注册失败");
        }

        return "ok";
    }

    public String login(LoginInfo loginInfo) {
//        省略校验

        User user = userDao.login(loginInfo.getTel(), loginInfo.getPassword());
//        登录成功之后需要获取角色
        if (ObjUtil.isEmpty(user)) {
            throw new BizException(406, "手机号或密码不正确");
        }
//        登录之后，需要返回token
        List<UserRoles> userRoles = userDao.selectRole(user.getId());
        List<String> roles = userRoles.stream().map(item -> item.getRoleName()).collect(Collectors.toList());

        Map<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("tel", user.getTel().substring(0, 4) + "****" + user.getTel().substring(8));
        map.put("nickName", user.getNickName());
        map.put("roles", roles);
        map.put(JWT.EXPIRES_AT, System.currentTimeMillis() + 2 * 24 * 60 * 60 * 1000);
        String token = JWTUtil.createToken(map, tokenKey.getBytes());
        return token;

    }
    public List<String> getPermission() {
        //省略校验
        int userId = LocalUserUtils.get().getId();
        return userDao.getPermission(userId);

    }

    private List<String> getRoles(Integer id) {
        List<Roles> roles = userRolesDao.selectRoleByUserId(id);
        List<String> res = roles.stream().map(Roles::getName).collect(Collectors.toList());
        return res;
    }
    public List<User> selectList(UserQuery query) {
        return userDao.selectList(query);
    }

    public int addRole(UserRoles userRoles) {
        if(userRoles.isHas()) return userRolesDao.delete(userRoles);
        return userRolesDao.insert(userRoles);
    }
}
